package cc

import (
	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
	"net/http"
)

// DetailInfo 返回
type DetailInfo struct {
	Code  int         `json:"code"`            // 状态码
	Msg   string      `json:"msg"`             // 返回信息
	Data  interface{} `json:"data"`            // 返回的数据
	Count string      `json:"count,omitempty"` // 返回的数据
}

type Handler interface {
	parse(detail *DetailInfo)
}
type HandleFunc func(*DetailInfo)

func (f HandleFunc) parse(detail *DetailInfo) {
	f(detail)
}
func WithCode(code int) HandleFunc {
	return func(detail *DetailInfo) {
		detail.Code = code
	}
}

func WithCount(count int64) HandleFunc {
	return func(detail *DetailInfo) {
		detail.Count = cast.ToString(count)
	}
}
func WithMsg(msg string) HandleFunc {
	return func(detail *DetailInfo) {
		detail.Msg = msg
	}
}
func WithData(data interface{}) HandleFunc {
	return func(detail *DetailInfo) {
		detail.Data = data
	}
}

func Return_success(c *gin.Context, infos ...Handler) {

	detail := &DetailInfo{
		Code:  1,
		Msg:   "请求成功",
		Data:  "",
		Count: "",
	}
	for _, info := range infos {
		// 接口函数调用闭包函数
		info.parse(detail)
	}
	c.AbortWithStatusJSON(http.StatusOK, detail)
}

func Return_fail(c *gin.Context, infos ...Handler) {

	detail := &DetailInfo{
		Code: 0,
		Msg:  "请求失败",
		Data: "",
	}
	for _, info := range infos {
		// 接口函数调用闭包函数
		info.parse(detail)
	}

	c.AbortWithStatusJSON(http.StatusOK, detail)
}

func Return_with_code(res bool, c *gin.Context, infos ...Handler) {

	if res == true {
		Return_success(c, infos...)
	} else {
		Return_fail(c, infos...)
	}

}
